//
//  CSFMDBTool.m
//  CarSalesMS_GCX
//
//  Created by Ssky on 2016/11/2.
//  Copyright © 2016年 Tony. All rights reserved.
//

#import "CSFMDBTool.h"

typedef enum _DBTables {
    tArrearage,
    tCommodityInfo,
    tGatheringDay,
    tInventoryInfo,
    tOrderInfo,
    tReturnInfo,
    tSaleInfo,
    tUserInfo,
} DBTables;

@interface CSFMDBTool ()

@property (nonatomic, strong) FMDatabaseQueue * dbQueue;

@end

@implementation CSFMDBTool {
    NSString * _dbName;
}



+ (instancetype)SharedFmdbTool {
    static id _instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
        
    });
    
    return _instance;
}

#pragma mark open
- (BOOL)openDBwithDbName:(NSString *)dbName {
    _dbName = dbName;
    
    self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:dbName];
    
    if (![self.dbQueue openFlags]) {
        NSLog(@"error: db was not opend!");
        return NO;
    }
    //    NSLog(@"db opend success!");
    
    [self createTables];
    return YES;
}

#pragma mark createTables
- (void)createTables {
    
    NSString * sqlPath = [[NSBundle mainBundle] pathForResource:@"LKFX.sql" ofType:nil];
    
    NSString *sql_createTables = [NSString stringWithContentsOfFile:sqlPath encoding:NSUTF8StringEncoding error:NULL];
    
    [_dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        BOOL isCreated = [db executeStatements:sql_createTables];
        if (isCreated) {
            NSLog(@"create tables success!");
        }else {
            NSLog(@"create table failed! --error: %@", db.lastErrorMessage);
            *rollback = YES;
            return;
        }
    }];
    
}


#pragma mark //insertTest
- (void)insertTestWithSql:(NSString *)insertSql {
    
    [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        //
        if (![db executeStatements:insertSql]) {
            NSLog(@"insert failed:%@", [db lastErrorMessage]);
            *rollback = YES;
            return;
        }else {
            NSLog(@"insert ok");
        }
    }];
}

#pragma mark - loadData
- (NSArray<NSDictionary *> *)loadDataWithSql:(NSString *)sql {
//    NSLog(@"%@", sql);
    NSMutableArray * mArr = [NSMutableArray array];
    
    [self.dbQueue inDatabase:^(FMDatabase *db) {
        //
        FMResultSet * rs = [db executeQuery:sql];
        
        while (rs.next) {
            //
            NSMutableDictionary * mDict = [NSMutableDictionary dictionary];
            for (int i = 0; i < rs.columnCount; i++) {
                
                NSString * name = [rs columnNameForIndex:i];  //key
                NSString * obj = [rs objectForColumnIndex:i]; //value

                [mDict setValue:obj forKey:name];

            }
            
            [mArr addObject:mDict];
        }//while end
    }];
    
    return mArr.copy;
}


#pragma mark - updateTable
- (NSInteger)updateTableWithSql:(NSString *)sql {
    __block NSInteger lastInsertId = -1;
    [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        if (![db executeUpdate:sql]) {
            NSLog(@"updateError: %@", db.lastErrorMessage);
            *rollback = YES;
            return;
        }
        lastInsertId = (long)db.lastInsertRowId;
    }];
    
    return lastInsertId;
}

- (NSInteger)insertTestDataIntoDB {
    NSString * path = [[NSBundle mainBundle] pathForResource:@"insertTest.sql" ofType:nil];
    NSString * sql = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
    
    __block NSInteger lastinsertId = 0;
    [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        if (![db executeStatements:sql]) {
            NSLog(@"--insertTestDataIntoDB error: %@", db.lastErrorMessage);
            *rollback = YES;
            return;
        }
        lastinsertId = (long)db.lastInsertRowId;
    }];
    
    //    FMDatabase * db = [FMDatabase databaseWithPath:self.dbQueue.path];
    //
    //    if (![db executeStatements:sql]) {
    //        NSLog(@"--insertTestDataIntoDB error: %@", db.lastErrorMessage);
    //        return NO;
    //    }
    
    return lastinsertId;
}


@end



